package com.roy.giftools.utils;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import com.bumptech.glide.gifencoder.AnimatedGifEncoder;

/**
 * Created by ROY on 2017/7/10.
 */

public class ImageConverter {

    public ImageConverter() {
    }

    /**
     * 将图像合成为Gif动态图
     *
     * @param pathList    静态图像的路径数组
     * @param gifName     输出的Gif图文件名
     * @param delay       每一帧间隔的时间，单位为毫秒
     * @return 生成的Gif的路径
     */
    public String pic2gif(List<String> pathList, String gifName, int delay, int compressNum) {
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            AnimatedGifEncoder e = new AnimatedGifEncoder();
            e.setRepeat(0);
            e.setDelay(delay); //设置帧间间隔时间
            e.start(baos);
            //建立临时文件夹，用于存储压缩后的图像
            File tempFile = new File(Environment.getExternalStorageDirectory().getPath() + "/GIFTools/temp");
            if (!tempFile.exists()) tempFile.mkdir();
            for (int i = 0; i < pathList.size(); i++) {
                Bitmap bitmap = BitmapFactory.decodeFile(pathList.get(i)); // 读入需要播放的jpg文件
                String tempName = stringToMD5(pathList.get(i));
                String tempPath = Environment.getExternalStorageDirectory().getPath() + "/GIFTools/temp/" + tempName + ".jpg";
                //按照5倍比例压缩照片
                ImageCompress.compressBitmapToFile(bitmap, tempPath, compressNum); //生成压缩后的图像文件
                Bitmap compressedBitmap = BitmapFactory.decodeFile(tempPath); // 读入压缩后的图像文件
                e.addFrame(compressedBitmap);  //将压缩后的图像添加到帧中
            }
            e.finish();

            //检查输出文件夹是否存在
            File file = new File(Environment.getExternalStorageDirectory().getPath() + "/GIFTools");
            if (!file.exists()) file.mkdir();
            //检查命名冲突
            String path = Environment.getExternalStorageDirectory().getPath() + "/GIFTools/" + gifName + ".gif";
            File checkFile = new File(path);
            if (checkFile.exists()) {
                //若存在命名冲突，则删去前一个文件
                checkFile.delete();
            }
            //输出合成好的Gif图
            FileOutputStream fos = new FileOutputStream(path);
            baos.writeTo(fos);
            baos.flush();
            fos.flush();
            baos.close();
            fos.close();
            return path; //返回生成的Gif图的路径
        } catch (Exception e) {
            System.out.println( "jpgToGif Failed:");
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 将字符串转成MD5值
     * @param string 需要转换的字符串
     * @return 字符串的MD5值
     */
    public String stringToMD5(String string) {
        byte[] hash;

        try {
            hash = MessageDigest.getInstance("MD5").digest(string.getBytes("UTF-8"));
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return null;
        }

        StringBuilder hex = new StringBuilder(hash.length * 2);
        for (byte b : hash) {
            if ((b & 0xFF) < 0x10)
                hex.append("0");
            hex.append(Integer.toHexString(b & 0xFF));
        }

        return hex.toString();
    }

    /**
     * 删除临时文件夹里面的文件
     */
    public void clearTmpDir() {
        File dir = new File(Environment.getExternalStorageDirectory().getPath() + "/GIFTools/temp");
        if (!dir.exists() || !dir.isDirectory())
            return;

        for (File file : dir.listFiles()) {
            if (file.isFile())
                file.delete(); // 删除所有文件
        }
    }

}
